const knex = require('../lib/db')
const { routeFormat, buildMenuTree, buildTree } = require('./helper/route')
const RoleService = require('./role')

const baseCRUD = require('./helper/crud')

const Base = baseCRUD('sys_menu')

// 找到所有常量路由
async function findConstRoutes() {
  const routes = await Base.findAll().where('constant', 't')
  return routes.map(routeFormat)
}

// 找到角色对应的菜单
async function findRoutesByRoleIds(roleIds) {
  const routes = await Base.findAll().select('sys_menu.*').join('sys_role_menu', 'sys_menu.id', 'sys_role_menu.menu_id').whereIn('sys_role_menu.role_id', roleIds)

  return [...new Set(routes.map((item) => item.id))].map((id) => routes.find((item) => item.id === id))
}

// 找到用户对应的菜单并返回树形结构
async function getUserRoutes(userId) {
  const roleIds = await knex('sys_user_role').where('user_id', userId).select('role_id').pluck('role_id')

  const routes = await findRoutesByRoleIds(roleIds)
  return {
    routes: buildMenuTree(routes),
    home: 'home'
  }
}

// 找到用户对应的菜单并返回树形结构
async function getMenuTree() {
  const routes = await Base.findAll()

  return buildTree(routes)
}

// 根据角色编码获取角色对应的菜单id
async function getRoteIdsByRoleCode(roleCode) {
  const role = await RoleService.findAll().where('code', roleCode).orWhere('id', roleCode).first()
  const routes = await findRoutesByRoleIds([role.id])
  return routes.map((item) => item.id)
}

module.exports = {
  ...Base,
  findConstRoutes,
  findRoutesByRoleIds,
  getUserRoutes,
  getMenuTree,
  getRoteIdsByRoleCode
}
